package org.ccay.enumerable.mybatis;

import java.util.List;

import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.TypeHandlerRegistry;
import org.ccay.enumerable.EnumItem;
import org.ccay.enumerable.PlainEnumItem;
import org.ccay.enumerable.loader.JavaEnumLoader;
import org.springframework.beans.factory.InitializingBean;

public class EnumItemTypeHandlers implements InitializingBean {
	
	private SqlSessionFactory sqlSessionFactory;
	
	private JavaEnumLoader loader;

	public EnumItemTypeHandlers(JavaEnumLoader loader) {
		this.loader = loader;
	}

	public void setSqlSessionFactory(SqlSessionFactory sqlSessionFactory) {
		this.sqlSessionFactory = sqlSessionFactory;
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		TypeHandlerRegistry registry = sqlSessionFactory.getConfiguration().getTypeHandlerRegistry();
		List<Class<?>> enumTypes = loader.getEnumClasses();
		//for interface
		EnumItemTypeHandler handlerInterface = new EnumItemTypeHandler(EnumItem.class);
		registry.register(EnumItem.class, JdbcType.VARCHAR, handlerInterface);
		registry.register(EnumItem.class, JdbcType.INTEGER, handlerInterface);
		registry.register(EnumItem.class, JdbcType.NUMERIC, handlerInterface);
		//for plainEnumItem
		PlainEnumItemTypeHandler plainEnumItem = new PlainEnumItemTypeHandler();
		registry.register(PlainEnumItem.class, JdbcType.VARCHAR, plainEnumItem);
		registry.register(PlainEnumItem.class, JdbcType.INTEGER, plainEnumItem);
		registry.register(PlainEnumItem.class, JdbcType.NUMERIC, plainEnumItem);
		//fro enumClass
		for(Class<?> type : enumTypes){
			EnumItemTypeHandler handler = new EnumItemTypeHandler(type);
			registry.register(type, JdbcType.VARCHAR, handler);
			registry.register(type, JdbcType.INTEGER, handler);
			registry.register(type, JdbcType.NUMERIC, handler);
		}
	}
}
